<?php

	// connect to db
	require_once '../db/db.php';
	
	// process form request
	if(isset($_POST['submit'])) {
	
		// sanitize and validate user input
		// NOTE: DO NOT rely on HTML5 or js validation 
		
		$error = false;
		
		// user's name
		if($_POST['first_name'] != '' && !empty($_POST['first_name'])) {
		
			if(filter_var($_POST['first_name'], FILTER_SANITIZE_STRING)) {
			
				$first_name = filter_var($_POST['first_name'], FILTER_SANITIZE_STRING);
			
			}else{
			
				$message[] = '<p class="error">Please enter a valid name.</p>';	
				$error = true;
			
			}
			
			$last_name = filter_var($_POST['last_name'], FILTER_SANITIZE_STRING);
			$name = $first_name . ' ' . $last_name;
			$name = trim($name);
			
		}else{
		
			$message[] = '<p class="error">Please give your first name.</p>';
			$error = true;
		
		}
		
		// email address
		if($_POST['email'] != '' && !empty($_POST['email'])) {
		
			if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
			
				$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
				
				// check for unique email
				$sql = "SELECT email FROM users WHERE email = '" . $email . "'";
				$check = $db->query($sql)->fetchAll();
				
				if($check) {
				
					$message[] = '<p class="error">This email address is already in use. If you have forgot your login, <a href="/forgot">recover it here</a>.</p>';
					$error = true;
				
				}
			
			}else{
			
				$message[] = '<p class="error">Please provide a valid email address.</p>';
				$error = true;
			
			}
		
		}else{
		
			$message[] = '<p class="error">Please provide your email address.</p>';
			$error = true;
		
		}
		
		// username
		if($_POST['username'] != '' && !empty($_POST['username'])) {
		
			// check for correct length, more than 6, less than 12
			if((strlen($_POST['username']) < 6) xor strlen($_POST['username']) > 12) {
			
				$message[] = '<p class="error">Please choose a username that is between 6 and 12 characters.</p>';
				$error = true;
				
			// remove invalid characters
			}elseif(!eregi("^[a-zA-Z0-9\-\_]*$", $_POST['username'])) { 
				
				$message[] = '<p class="error">Usernames must contain only letters, numbers, hyphens(-) and underscores(_).</p>';
				$error = true;
							
			}else{
				 
				// validate username
				$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
				
				// check for unique username
				$sql = "SELECT username FROM users WHERE username = '" . $username . "'";
				$check = $db->query($sql)->fetchAll();
				
				if($check) {
				
					$message[] = '<p class="error">The username <strong>' . $_POST['username'] . '</strong> is already in use.</p>';
					$error = true;
				
				}
			
			}
		
		}else{
		
			$message[] = '<p class="error">Please provide a username.</p>';
			$error = true;
		
		}
		
		// validate password
		if($_POST['password'] != '' && !empty($_POST['password'])) {
		
			// check that both passwords match
			if($_POST['password'] == $_POST['pass_check']) {
			
				// sanitize password
				$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
			
			}else{
			
				$message[] = '<p class="error">Passwords do not match. Please retype both passwords.</p>';
				$error = true;
			
			}
		
		}else{
		
			$message[] = '<p class="error">Please enter a password.</p>';
			$error = true;
		
		}
		
		// validate slideLock
		if(isset($_POST['js_check']) && $_POST['js_check'] == 0) { // check for javascript
		
			// no js, proceed with server side validation
			$slideLock = true;
		
		}else{
		
			// check slider input
			if(isset($_POST['sliderInput']) && $_POST['sliderInput'] == 10) {
			
				$slideLock = true;
			
			}else{
			
				$slideLock = false;
				$message[] = '<p class="error">Please unlock the form before submitting.</p>';
				$error = true;
			
			}
		
		}
		
		// create new user account
		if($error == false && $slideLock == true) {
			
			$send = false;
			
			$password = md5($password);
			$sql = "INSERT INTO users (username, password, date_created, email, name) VALUES ('" . $username . "', '" . $password . "', NOW(), '" . $email . "', '" . $name . "')";
			
			try {
				
				// add user to db
				$db->beginTransaction();
				$db->exec($sql);
				$db->commit();
				$send = true;
			
			} catch(PDOException $e) {
			
				$send = false;
				$db->rollBack();
				$message[] = '<p class="error">Could not create user account. Please try again later.</p>';
				$message[] = '<pre>' . $e->getMessage() . '</pre>';
			
			}
			
			if($send == true) { 
			
				// send confirmation email
				// TODO: change this to the PEAR package when template is finished
				$to = $email;
				$subject = "Welcome to AtBat";
				$body = '<html>
								<head>
									<title>Welcome to AtBat</title>
								</head>
								<body>
									<p>Thank you for joining AtBat. Provided in this email is a link to confirm your account. <em>You must confirm your account before you can use AtBat</em>.</p>
									<p><a href="http://atbat.smullinstudios.com/confirm/' . md5($username) . '">Confirm your account</a></p>
								</body>
							</html>';
							
				$headers  = 'MIME-Version: 1.0' . "\r\n";
				$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
				$headers .= 'To: ' . $name . ' <' . $email . '>' . "\r\n";
				$headers .= 'From: AtBat <noreply@smullinstudios.com>' . "\r\n";
				
				$mail = (mail($to, $subject, $body, $headers) ? $message[] = '<p class="success">User account has been created. We have sent your confirmation email.</p>' : $message[] = '<p class="error">Could not send your confirmation email. Please confirm your account <a href="confirm/' . md5($username) . '">here</a>.</p>');
			
			}
		
		}
	
	}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <base href="http://localhost/atbat/html/" />
	<meta charset="utf-8">
	<title>AtBat :: Sign Up</title>
	<meta name="description" content="">
	<meta name="author" content="Sean Mullin, http://parametercontraption.com">
	<!--  Mobile Viewport Fix j.mp/mobileviewport & davidbcalhoun.com/2010/viewport-metatag -->
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
	<link rel="shortcut icon" href="images/design/favicon.ico">
	<link rel="apple-touch-icon" href="images/design/apple-touch-icon.png">
	<link rel="stylesheet" href="css/screen.css">
	<!-- For the less-enabled mobile browsers like Opera Mini --><link rel="stylesheet" media="screen" href="css/slideLock.css">
    <script src="js/modernizr-1.5.min.js"></script>
</head>
<body>
	<?php require_once 'include/header.html'; ?>
    <section id="content">
    	<p>Use the form below to create your user profile. Once complete you will be able to create and user players as well as score games and track stats.</p>
        <form action="" method="post" id="signup">
        	<?php if(isset($message)) foreach($message as $m) print $m; ?>
        	<fieldset>
            	<legend>Sign Up</legend>
                <p><label for="first_name">First Name:</label><input type="text" name="first_name" id="first_name" value="<?php if(isset($_POST['first_name'])) { echo $_POST['first_name']; } ?>" required /></p>
                <p><label for="last_name">Last Name:</label><input type="text" name="last_name" id="last_name" value="<?php if(isset($_POST['last_name'])) { echo $_POST['last_name']; } ?>" /></p>
                <p><label for="email">Email:</label><input type="email" name="email" id="email" placeholder="example@example.com" required value="<?php if(isset($_POST['email'])) { echo $_POST['email']; } ?>" required /></p>
                <p><label for="username">Choose a Username:</label><input type="text" name="username" id="username" maxlength="12" value="<?php if(isset($_POST['username'])) { echo $_POST['username']; } ?>" placeholder="6 to 12 characters please" /><div id="user_status"></div></p>
                <p><label for="password">Choose a Password:</label><input type="password" name="password" id="password" value="<?php if(isset($_POST['password'])) { echo $_POST['password']; } ?>" required maxlength="12" /><div id="pass_status"></div></p>
                <p><label for="pass_check">Retype Password:</label><input type="password" name="pass_check" id="pass_check" value="<?php if(isset($_POST['pass_check'])) { echo $_POST['pass_check']; } ?>" required maxlength="12" /></p>
                <input type="submit" name="submit" value="Create Profile" id="submit" />
                <input type="hidden" name="js_check" id="js_check" value="0" />
            </fieldset>
        </form>
    </section>
    <?php require_once 'include/footer.html'; ?>
    <script src="js/user_check.js"></script>
</body>
</html>